#include <unistd.h>
#include <string>
#include <iostream>
#include <libgearman/gearman.h>

using namespace std;

int main(int argc,char* argv[])
{
    in_port_t port = 0;
    string host("10.61.0.145");
    string url(argv[1]);
    gearman_return_t ret;
    gearman_client_st client;

    if (gearman_client_create(&client) == NULL)
    {
        cerr<<"Memory allocation failure on client creation"<<endl;
        exit(1);
    }
    cout<<"client created."<<endl;

    ret= gearman_client_add_server(&client, host.c_str(), port);
    if (ret != GEARMAN_SUCCESS)
    {
        cerr<<gearman_client_error(&client)<<endl;
        exit(1);
    }
    cout<<"client add server:"<<host<<endl;

    char *result;
    size_t result_size;
    while (1)
    {
        result= (char *)gearman_client_do(&client, "larbin", NULL,
                                          (void*)url.c_str(),//workload
                                          (size_t)url.length(),//workload size
                                          &result_size, &ret);
        if (ret == GEARMAN_WORK_DATA)
        {
            cout<<"Data="<<result<<endl;
            free(result);
            continue;
        }
        else if (ret == GEARMAN_WORK_STATUS)
        {
            uint32_t m,n;
            gearman_client_do_status(&client, &n, &m);
            printf("Status: %u/%u\n", n, m);
            continue;
        }
        else if (ret == GEARMAN_SUCCESS)
        {
            cout<<"Result="<<result<<endl;
            free(result);
        }
        else if (ret == GEARMAN_WORK_FAIL)
            cerr<<"Work failed"<<endl;
        else
            cerr<<gearman_client_error(&client)<<endl;

        break;
    }

    gearman_client_free(&client);

    return 0;
}


